import Vue from "vue";
import Vuex from "vuex";

import dynamicRoutes from "../router/dynamicRoutes";
import allRoutes from "../router/allRoutes";
import recursionRoutes from "../utils/recursionRoutes";
import * as api from "../api/index";
import router from "../router";

Vue.use(Vuex);

let userInfo = localStorage.getItem("qf-info") || "{}";
export default new Vuex.Store({
  state: {
    userInfo: JSON.parse(userInfo),
    isCollapse: false,
    sideMenu: [],
  },
  mutations: {
    //存储用户信息
    SETUSERINFO(state, payload) {
      state.userInfo = payload;
    },
    //改变菜单栏展开和关闭
    CHANGEMENU(state) {
      state.isCollapse = !state.isCollapse;
    },
    //设置左边菜单栏
    SET_SIDE_MENU(state, payload) {
      state.sideMenu = [...payload];
      //将获取的用户动态路由添加到"/"路由的children中
      let target = dynamicRoutes.find((item) => item.path === "/");
      target.children = [...payload];
      console.log(dynamicRoutes);
      //将dynamicRoutes中的路由添加到用户显示的路由中(index.js)
      //利用的是addRoutes方法
      router.addRoutes(dynamicRoutes);
    },
  },
  actions: {
    //获取用户权限的菜单路由
    GET_MENU({ commit }) {
      return api
        .menuListApi() //调用定义好的接口请求用户权限菜单的数据
        .then((res) => {
          let menuList = res.data.menuList; //后台返回的用户权限菜单
          let userMenuList = recursionRoutes(allRoutes, menuList); //调用计算用户权限菜单的方法，得到当前用户的权限菜单
          commit("SET_SIDE_MENU", userMenuList); //提交，将权限菜单数据给state中的属性
        });
    },
  },
  modules: {},
});
